const express = require("express");
const router = express.Router();
const dayjs = require("dayjs");
const utc = require("dayjs/plugin/utc");
const timezone = require("dayjs/plugin/timezone");

dayjs.extend(utc);
dayjs.extend(timezone);

let connectDAO = require("./connect.js");

// 获取自习室列表
router.get("/get_study_rooms", function (req, res) {
  const {
    page = 1,
    pageSize = 10,
    RoomID,
    RoomName,
    Status
  } = req.query;

  // 参数验证
  const pageNum = parseInt(page);
  const pageSizeNum = parseInt(pageSize);
  if (isNaN(pageNum)) pageNum = 1;
  if (isNaN(pageSizeNum)) pageSizeNum = 10;
  const offset = (pageNum - 1) * pageSizeNum;

  // 基础查询
  let baseSql = "SELECT * FROM StudyRoom";
  let countSql = "SELECT COUNT(*) AS total FROM StudyRoom";
  const conditions = [];

  // 筛选条件（保持你原有的条件拼接方式）
  if (RoomID) {
    conditions.push(`RoomID = '${RoomID}'`);
  }
  if (RoomName) {
    conditions.push(`RoomName LIKE '%${RoomName}%'`);
  }
  if (Status) {
    conditions.push(`Status = '${Status}'`);
  }

  // 拼接WHERE条件
  if (conditions.length > 0) {
    const whereClause = " WHERE " + conditions.join(" AND ");
    baseSql += whereClause;
    countSql += whereClause;
  }

  // 分页查询
  const finalSql = `${baseSql} LIMIT ${pageSizeNum} OFFSET ${offset}`;

  // 先查询总数
  connectDAO.queryDataBySQL(countSql, (countResult) => {
    const total = countResult[0].total;

    // 再查询分页数据
    connectDAO.queryDataBySQL(finalSql, (records) => {
      res.send({
        code: 200,
        msg: "Success",
        data: {
          records,
          pagination: {
            current: pageNum,
            pageSize: pageSizeNum,
            total: total
          }
        }
      });
    });
  });
});

// 新增自习室
router.post("/add_study_room", (req, res) => {
  const { RoomName, TotalSeats, Status } = req.body;
  const sql = `INSERT INTO StudyRoom (RoomName, TotalSeats, Status) 
              VALUES ('${RoomName}', '${TotalSeats}', '${Status}')`;
  connectDAO.queryDataBySQL(sql, (records) => {
    if (records.affectedRows > 0) {
      res.send({
        code: 200,
        msg: "Success",
      });
    } else {
      res.send({
        code: 200,
        msg: "no data",
      });
    }
  })
});

// 更新自习室信息
router.put("/update_study_room", function (req, res) {
  const { RoomName, TotalSeats, Status, RoomID } = req.body;
  const sql = `UPDATE StudyRoom SET RoomName = '${RoomName}', TotalSeats = ${TotalSeats}, Status = '${Status}' WHERE RoomID = ${RoomID}`;
  connectDAO.queryDataBySQL(sql, (records) => {
    if (records.affectedRows > 0) {
      res.send({
        code: 200,
        msg: "Success",
      });
    } else {
      res.send({
        code: 200,
        msg: "no data",
      });
    }
  })
});

// 删除自习室
router.delete("/delete_study_room/:RoomID", function (req, res) {
  const { RoomID } = req.params;
  let sql = `DELETE FROM StudyRoom WHERE RoomID = ${RoomID}`;
  connectDAO.queryDataBySQL(sql, (records) => {
    if (records.affectedRows > 0) {
      res.send({
        code: 200,
        msg: "Success"
      })
    }
  })
})

module.exports = router;
